import { Box, Divider, ListItem, Typography, Chip, List } from "@mui/material";
import { styled } from "@mui/material/styles";
import React, { useState, useEffect } from "react";
import { useOutletContext, redirect } from "react-router-dom";
import {
  RowFlexBoxCS,
  RowFlexBoxSC,
  ColumnFlexBoxSC,
  ReturnButton,
} from "../../components/common/Common.jsx";
import { getLawRootStorage } from "../../localCache/legalContentStorage.js";
import SideBarLegislation from "./SideBarLegislation.jsx";
import LegislationList from "./LegislationList.jsx";
import { CHINESE_SHOW_MODEL } from "./Common.jsx";
import "../../css/common.css";
import { searchAdvancedFullText } from "../../api/searchLaw.js";
import { getSearchDataCache } from "../../localCache/searchCache.js";
import Loading from "../../components/loading/Loading.jsx";

/**
 * Loader for Root
 * @returns {object} various data to be used by Root component
 */
export async function loader() {
  const lawRoot = await getLawRootStorage();
  return { lawRoot };
}

/**
 * advancedSearch in action function
 * @param {request} request data
 * @returns redirect if successful, id if failed
 */
export async function action({ request }) {
  const formData = await request.formData();
  console.log(formData);
  const formattedData = JSON.parse(formData.get("formattedData"));
  const res = { fail: true };
  res.err = await searchAdvancedFullText(formattedData);
  if (res.err.length > 0) {
    return res;
  } else {
    return redirect(`/fayucz/legislation`);
  }
}
/**
 * 这是一个展示法律条文的主文件
 * @returns
 */
export default function LegalDocumentsHubShow() {
  const {
    setSearchCondition,
    searchData,
    advancedSearchResult,
    setSearchData,
    searchCondition,
    handleSubmit,
    setIsVisible,
  } = useOutletContext();

  //获取法律基本数据
  const lawsInfo =
    JSON.stringify(advancedSearchResult.searchedRoots) === "{}"
      ? advancedSearchResult.searchRes
      : advancedSearchResult.searchedRoots.laws;

  //自定义style使列表元素在水平上均匀排列
  const StyledList = styled(List)(() => ({
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    listStyle: "none",
    padding: 0,
    ml: 1,
  }));

  const [isLoading, setIsLoading] = useState(true);

   // 添加返回顶部功能
   const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth', // 平滑滚动
    });
  };

  // 刷新后重新发起请求
  useEffect(() => {
    const fetchData = async () => {
      //获取searchData的缓存数据
      let searchDataCache = await getSearchDataCache();
      //重新设置状态、发起请求，保证页面不会刷掉
      setSearchData(searchDataCache);
      handleSubmit(searchDataCache);
      if (searchDataCache) {
        setIsLoading(false);
      }
    };
    fetchData();
    //设置搜索框可见
    setIsVisible(true);
    // 清理函数，在组件卸载时执行
    return () => {
      setIsVisible(false);
    };
  }, []);

  if (isLoading) {
    return <Loading />;
  }

  /**
   * 点击侧边栏获取搜索条件
   * @param {string} searchConditionKey
   * @param {string} searchConditionValue
   */
  // 定义 handleSearch 函数, 将条件append到searchData中去
  const handleAdvancedSearch = (searchConditionKey, searchConditionValue) => {
    setSearchData((currentSearchData) => {
      let newSearchData = { ...currentSearchData };

      if (searchConditionKey === "publishedAt") {
        const year = parseInt(searchConditionValue, 10);
        newSearchData = {
          ...newSearchData,
          publishStartDate: new Date(year, 0, 1),
          publishEndDate: new Date(year, 11, 31),
        };
      } else {
        newSearchData[searchConditionKey] = searchConditionValue;
      }

      return newSearchData;
    });
  };

  //对检索条件做删除操作，保持两个变量的统一
  const handleDelete = (itemKey) => {
    setSearchCondition((currentConditions) => currentConditions.filter((item) => Object.keys(item)[0] !== itemKey)
    );

    const currentData = { ...searchData };

    if (Object.keys(currentData).length > 0) {
      const deleteKeys =
        itemKey === "publishedAt"
          ? ["publishStartDate", "publishEndDate"]
          : itemKey === "true" || itemKey === "false"
          ? ["fullText", "keywords"]
          : [itemKey];

      deleteKeys.forEach((key) => delete currentData[key]);

      setSearchData(currentData);
    }
  };

  return (
    <ColumnFlexBoxSC
      className="container"
      sx={{
        width:"95%",
        height: "auto",
        maxWidth: "1200px"
      }}
    >
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          width: "100%",
          my: 1,
        }}
      >
        <Box sx={{ width: "100%", mb: "10px" }}>
          <RowFlexBoxSC sx={{ minHeight: "52px" }}>
            <Typography variant="body" sx={{ ml: 2, mt: "20px", padding: 0 }}>
              检索条件：
            </Typography>
            <StyledList>
              {searchCondition &&
                searchCondition.map((item, index) => (
                  <ListItem key={index} sx={{ mt: "20px", padding: 0, ml: 1 }}>
                    <Chip
                      label={`${
                        CHINESE_SHOW_MODEL[Object.keys(item)]
                      }: ${Object.values(item)}`}
                      sx={{
                        color: (theme) => theme.palette.primaryContrast.main,
                      }}
                      onDelete={() => handleDelete(Object.keys(item)[0])}
                    />
                  </ListItem>
                ))}
            </StyledList>
          </RowFlexBoxSC>
        </Box>
        <RowFlexBoxSC>
          <Typography
            variant="body"
            sx={{ mr: 2, padding: 0, whiteSpace: "nowrap" }}
          >
            已为您找到法律<span> {lawsInfo.length} </span>部
          </Typography>
        </RowFlexBoxSC>
      </Box>

      <Box
        sx={{
          width: "100%",
          mb: "20px",
          background: "#ffffff",
          borderRadius: "15px",
          zIndex: 0,
          position: "relative",
        }}
      >
        <RowFlexBoxCS
          sx={{
            height: "100%",
            minHeight: "1000px",
            backgroundColor: (theme) => theme.palette.background.main,
            m: "20px",
            borderRadius: "10px",
          }}
        >
          {/* 侧边栏检索组件 */}
          <Box sx={{ width: "25%" }}>
            <SideBarLegislation
              handleAdvancedSearch={handleAdvancedSearch}
              lawsInfo={lawsInfo}
            />
          </Box>
          {/*分割线 */}
          <Divider
            sx={{ minHeight: "1000px", m: 0.5, height: "100%" }}
            orientation="vertical"
          />
          {/*法条等内容的列表*/}
          <Box
            sx={{
              width: "75%",
              ml: "20px",
            }}
          >
            <Box>
              <LegislationList
                advancedSearchResult={advancedSearchResult}
                searchData={searchData}
              />
            </Box>
          </Box>
        </RowFlexBoxCS>
      </Box>
        {/* 返回顶部按钮 */}
        <ReturnButton scrollToTop={scrollToTop}/>
    </ColumnFlexBoxSC>
  );
}
